package com.viego.financialrecommendsystem.controller;

import com.viego.financialrecommendsystem.common.AjaxResult;
import com.viego.financialrecommendsystem.common.BaseContext;
import com.viego.financialrecommendsystem.entity.AccessRecord;
import com.viego.financialrecommendsystem.entity.Article;
import com.viego.financialrecommendsystem.entity.Discuss;
import com.viego.financialrecommendsystem.entity.User;
import com.viego.financialrecommendsystem.service.IArticleService;
import com.viego.financialrecommendsystem.service.IDiscussService;
import com.viego.financialrecommendsystem.service.IUserService;
import com.viego.financialrecommendsystem.utils.EmailSendUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.security.x509.AlgIdDSA;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:8081", allowCredentials = "true")
public class UserController {

    @Resource
    IUserService userService;


    /**
     * 用户登录的接口
     * 测试通过
     * @param user 用户实体类
     * @return user 对应的 json 数据
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody User user , HttpServletRequest request){
        log.info("正在尝试登录......");
        User login_user = userService.login(user);
        if (login_user != null){
            if (login_user.getStatus() == 1){
                HttpSession session = request.getSession();
                session.setAttribute("UID",login_user.getUserId());
                System.out.println(request.getSession().getAttribute("UID"));
                return AjaxResult.success("登录成功",login_user);
            }else{
                return AjaxResult.error("用户未激活,请前往邮箱激活");
            }

        }else{
            return AjaxResult.error("登录失败，用户名或密码错误");
        }
    }

    /**
     * 用户退出登录
     * @param request HttpServletRequest
     * @return string
     */
    @GetMapping("/logout")
    public AjaxResult logout(HttpServletRequest request){
        log.info("UID={}的用户正在退出登录.....",request.getSession().getAttribute("UID"));
        request.getSession().removeAttribute("UID");
        log.info("退出成功");
        return AjaxResult.success("退出成功");
    }

    /**
     * 根据用户的uid资产
     * @param userId 用户的 id
     * @return 用户的资产
     */
    @PostMapping("/assets")
    public AjaxResult assets(@RequestBody String userId){
        // TODO For input string: "1="
        userId = userId.substring(0,userId.length()-1);
        log.info("正在获取资产 UID = {}",userId);
        Integer assets = userService.getassets(Long.parseLong(userId));
        return AjaxResult.success("查询成功",assets);
    }

    /**
     * 添加访问记录对象，并不是每一次都添加
     * 当 Product.vue 组件被销毁的时候，我们再进行添加
     * @param record 访问记录对象
     * @return true 添加成功 false 添加失败
     */
    @PostMapping("/record")
    public AjaxResult record(@RequestBody List<AccessRecord> record){
        //每一次访问产品，都添加一次访问记录，以此来记录用户对产品的偏好
        boolean flag = userService.addRecord(record);
        if (flag){
            //添加成功
            return AjaxResult.success("添加成功");
        }else{
            return AjaxResult.error("添加失败");
        }
    }

    /**
     * 上传头像
     */
    @PostMapping("/upload")
    public AjaxResult uploadImg(@RequestParam("avatar")MultipartFile avatar,
                                @RequestParam("id")String id,
                                @RequestParam("preImg")String preImg){
        //文件路径
        String filePath = "D:\\Financial-Recommendation-Project\\gitee\\financial-recommend\\upload\\img\\";
        //上传路径（用于文件的删除）
        String upload = "D:\\Financial-Recommendation-Project\\gitee\\financial-recommend\\upload\\upload\\";
        if (avatar.isEmpty()){
            return AjaxResult.error("文件为空，上传失败");
        }
        //图片名字
        //文件名 = 当前事件（精确到毫秒） +  原来文件的名称
        String fileName = System.currentTimeMillis() + avatar.getOriginalFilename();
        // 获取当前日期
        LocalDate currentTime = LocalDate.now();
        int year = currentTime.getYear();
        int month = currentTime.getMonthValue();
        int day = currentTime.getDayOfMonth();
        String dirY = year + "";
        String dirM = month <= 9? "0" + month :"" +  month;
        String dirD = day <= 9? "0" + day : "" + day;
//        String childDIR = +year+"-"+month+"-"+day;
        File file1 = new File(upload +"\\" + dirY + "\\" + dirM + "\\" + dirD);
        if (!file1.exists()){//如果文件路径不存在，就创建一个
            file1.mkdirs();
        }
//        File file = new File(filePath + childDIR);
//        if (!file.exists()){
//            file.mkdir();
//        }
        //文件地址
        File dest = new File(upload +"\\" + dirY + "\\" + dirM + "\\" + dirD + "\\" + fileName);
        //保存到数据库的文件地址
        String string_avatar_path = "/profile/upload/" +dirY + "/" + dirM + "/" + dirD +"/"+ fileName;
        Long currentId = BaseContext.getCurrentId();
        log.info("当前修改图片的用户UID = {}",currentId);
        userService.updateCommentImg(currentId,string_avatar_path);
        boolean flag = false;
        try {
            avatar.transferTo(dest);
            User user = new User();
            user.setUserId(Long.parseLong(id));
            user.setImg(string_avatar_path);
            flag = userService.save(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (flag){
            //当图片上传成功之后，就删除掉之前的图片
            // 删除之前的图片
            File previousImage = new File(upload + preImg);
            if (previousImage.exists()) {//如果图片存在
                previousImage.delete();
            }
            return AjaxResult.success("上传成功了捏! ~~");

        }else{
            return AjaxResult.error("上传失败");
        }
    }


    @GetMapping("/info")
    public AjaxResult info (@RequestParam("userId") Long userId){
        User user = userService.info(userId);
        return AjaxResult.success("查询成功",user);
    }

    /**
     * 获取我收藏的文章
     * @param userId 用户ID
     * @return 文章列表
     */
    @GetMapping("/article")
    public AjaxResult article(@RequestParam("userId") String userId){
        List<Article> list = userService.getArticle(userId);
        return AjaxResult.success("查询成功",list);
    }

    /**
     * 获取我收藏的讨论
     * @param userId 用户ID
     * @return 文章列表
     */
    @GetMapping("/discuss")
    public AjaxResult discuss(@RequestParam("userId") String userId){
        List<Discuss> list = userService.getDiscuss(userId);
        return AjaxResult.success("查询成功",list);
    }

    @GetMapping("/deleteArticle")
    public AjaxResult deleteArticle(@RequestParam("articleId")String articleId){
        boolean flag = userService.deleteArticle(Long.parseLong(articleId));
        if (flag){
            return AjaxResult.success("删除成功");
        }else{
            return AjaxResult.error("删除失败");
        }
    }

    @GetMapping("/deleteDiscuss")
    public AjaxResult deleteDiscuss(@RequestParam("discussId")String discussId){
        boolean flag = userService.deleteDiscuss(Long.parseLong(discussId));
        if (flag){
            return AjaxResult.success("删除成功");
        }else{
            return AjaxResult.error("删除失败");
        }
    }

    @PostMapping("/register")
    public AjaxResult register(@RequestBody User user){
        //先检查用户名是否可用
        boolean flag = userService.isUsed(user.getUsername());
        if (!flag){
            //可以使用
            String code = System.currentTimeMillis()+"";
            user.setCode(code);
            String content = "http://localhost:8888/FinancialRecommend/user/active?code="+code;
            EmailSendUtil.sendEmailAsync(user.getEmail(),"账户激活",content);
            userService.register(user);
            return AjaxResult.success("注册成功，请前往邮箱激活");
        }else{
            //不可以使用
            return AjaxResult.error("用户名不可用");
        }
    }

    @GetMapping("/active")
    public String active(@RequestParam("code")String code){
        boolean flag = userService.active(code);
        if (flag){
            return "激活成功";
        }else{
            return "激活失败";
        }
    }

    @GetMapping("/charge")
    public AjaxResult charge(@RequestParam("userId")String userId,
                             @RequestParam("charge")String charge){
        boolean flag = userService.charge(userId,charge);
        if (flag){
            return AjaxResult.success("充值成功");
        }else{
            return AjaxResult.error("充值失败");
        }
    }

}
